var express = require("express")
var router = express.Router()
var QcloudSms = require("qcloudsms_js")
var connection = require("../../../db/sql")
var jwt = require("jsonwebtoken")
const bcrypt = require("bcryptjs")
var listSql = require("./listSql")
const { RecommendUserService, RecommendGoodsService } = require("./cfa")

/*获取分类首页数据值*/
router.get("/api/list/getlistdata", function (req, res, next) {
  let shopList = []
  let token = req.headers.token
  let tokenObj = jwt.decode(token)
  let recommData = []
  connection.query(listSql.selectListLeftData(), function (err, resluts) {
    if (err) {
      res.send({
        msg: "查询错误",
        data: err,
      })
    }

    connection.query(listSql.selectListRightData(), function (error, reslut) {
      if (err) {
        res.send({
          msg: "查询错误",
          data: err,
        })
      }

      /*数据生成
      1 获取当前用户的id
      2 获取所有的购买商品用户的用户id和商品id
      */
      // const recommendGoodsService = new RecommendGoodsService(data1) // 生成个性化推荐
      // const result1 = recommendGoodsService.start()
      let user_id = ""
      let dataBaseData = []
      if (tokenObj) {
        connection.query(listSql.selectUserId(tokenObj), function (err, arr) {
          if (err) {
            res.send({
              code: 206,
              msg: "查询错误",
              err,
            })
          }
          user_id = arr[0].user_id
          console.log("user_id的值")
          console.log(user_id)

          // 第二部
          connection.query(listSql.selectUserGoPay(), function (err, resl) {
            if (err) {
              res.send({
                code: 207,
                msg: "查询错误",
                err,
              })
            }
            // dataBaseData = resl

            let data2 = resl
            let arr = []
            data2.map((item) => {
              console.log(`====`)
              let obj = {}
              console.log(item)
              obj.userId = item.ordernumber_user_id
              obj.goodsId = item.orderfrom_list_id
              console.log(obj)
              arr.push(obj)
              obj = {}
            })
            console.log(`finaally`)
            console.log(arr)
            const recommendUserService = new RecommendUserService(
              arr,
              user_id,
              100
            )
            const result1 = recommendUserService.start()
            console.log(result1)
            if (result1.length != 0) {
              // 根据Id遍历list中的数据
              result1.forEach((v, index) => {
                try {
                  connection.query(
                    listSql.selectRecommedData(v),
                    (errs, shop) => {
                      let shops = JSON.parse(JSON.stringify(shop))
                      console.log("查询结果")
                      console.log(shops)
                      recommData.push(...shops)
                      console.log("推荐商品的数组")
                      console.log(recommData)
                      // 判断数组是否最后循环
                      if (result1.length - 1 == index) {
                        res.send({
                          status: 200,
                          msg: "用户登录且推荐数据不为空推荐列表查询成功",
                          data: {
                            recommData,
                            reslut,
                          },
                        })
                      }
                    }
                  )
                } catch (e) {
                  console.log(`查询出错${e}`)
                }
              })

              // res.send({
              //   status: 200,
              //   msg: "用户登录且推荐数据不为空推荐列表查询成功",
              //   data: {
              //     recommData,
              //     reslut,
              //   },
              // })
            } else if (result1.length == 0) {
              res.send({
                status: 200,
                msg: "用户登录且推荐数据为空推荐列表查询成功",
                data: {
                  recommData,
                  reslut,
                },
              })
            }
          })
        })
      } else {
        // 没有登录展示所有数据
        res.send({
          status: 200,
          msg: "用户没有登录时的推荐列表",
          data: {
            recommData,
            reslut,
          },
        })
      }
    })

    console.log(shopList)
  })
})

/*初始化数据*/
router.get("/api/list/getinit", function (req, res, next) {
  // let id = req.body.id
  // console.log(id)
  connection.query(listSql.selectInit(), function (err, resluts) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询出错",
        err,
      })
    }

    res.send({
      code: 200,
      msg: "查询成功",
      data: resluts,
    })
  })
})

router.post("/api/list/getitemdata", function (req, res, next) {
  let id = req.body.id
  console.log(id)
  connection.query(listSql.selectItemData(id), function (err, reslut) {
    if (err) {
      res.send({
        code: 201,
        msg: "查询出错",
        err,
      })
    }
    res.send({
      code: 200,
      msg: "查询成功",
      data: reslut,
    })
  })
})
router.post("/api/list/shoplistdetails", function (req, res, next) {
  let id = req.body.id
  console.log(id)
  connection.query(listSql.selectItemData(id), function (err, reslut) {
    let obj = {}
    if (err) {
      res.send({
        code: 201,
        msg: "查询信息失败",
        err,
      })
    }
    obj.information = reslut[0]
    // 查询图片
    connection.query(listSql.selectPics(id), function (errs, resluts) {
      if (err) {
        res.send({
          code: 201,
          msg: "查询信息失败",
          err,
        })
      }
      obj.imgs = resluts
      console.log(obj)
      res.send({
        code: 200,
        mesg: "查询成功",
        data: obj,
      })
    })
  })
})

module.exports = router
